
import axios, { AxiosRequestConfig, AxiosResponse,AxiosInstance } from 'axios';
import { showMessage } from "../utils/axios/status";   // 引入状态码文件
import {Notify} from 'vant'

class HttpRequest{
	public baseURL: string|undefined|boolean;
	public timeout: number;
	instance!: AxiosInstance;
	constructor(){
		this.baseURL = import.meta.env.VITE_AXIOSURL
		this.timeout = 30000; //30s请求超时
	}
	//请求拦截
	setInterceptors(instance:any){
		//请求
		instance.interceptors.request.use( (config: AxiosRequestConfig) =>{
			config.headers = {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',        // 传参方式
				'Accept': 'application/json'
			}
			//获取sessionsId 没有就调整登录页
			return config
		}, (error: any) =>{
			return Promise.reject(error)
		});
		//响应
		instance.interceptors.response.use((res:AxiosResponse)=>{
			let data = res?res.data:res
	
			if(data.code==0){
				console.log(data)
				return Promise.resolve(data.data)
			}else{
				return Promise.reject(data.data)
			}
		},(error:any)=>{
			let status = error.response.status;
			let message =	showMessage(status); 
			Notify({ type: 'danger', message:message });
			return Promise.reject(error);
		})
	}
	mergeOptions(options:any){
		this.baseURL = import.meta.env.VITE_AXIOSURL

		return {baseURL: this.baseURL,timeout:this.timeout, ...options}
	}
	request(options:any){
		this.instance = axios.create();
		this.setInterceptors(this.instance);
		const opts = this.mergeOptions(options);
		return this.instance(opts)
	}
	get(url:string, config?:any){
		return this.request({
			method: "get",
			url,
			...config
		})
	}
	post(url:string,data: Object, config?:any){
		return this.request({
			method: "post",
			url,
			data,
			...config
		})
	}
	put(url:string, data: Object,config?:any){
		return this.request({
			method: "put",
			url,
			data,
			...config
		})
	}
	del(url:string,data: Object, config?:any){
		return this.request({
			method: "delete",
			url,
			data,
			...config
		})
	}
}
export default new HttpRequest;
